var Skink; if (!Skink) Skink = {};

/***********
Skink.UI
***********/
if (!Skink.Keyboard) Skink.Keyboard = {};

Skink.Keyboard.setShortcuts = function() {
    air.trace('Setting keyboard shortcuts');
    Skink.dump("Setting Shortcuts=================================================")
    Skink.dump("os: " + air.Capabilities['os']);

    var Modkey = 'Meta';

    if (air.Capabilities['os'].search(/Windows/i) != -1) {
        Skink.dump('THIS IS WINDOWS');
        Modkey = 'Ctrl';
    } else if (air.Capabilities['os'].search(/Linux/i) != -1) { // thx agolna
        Skink.dump('THIS IS LINUX');
        Modkey = 'Ctrl';
    } else if (air.Capabilities['os'].search(/Mac/i) != -1) {
        Skink.dump('THIS IS MACOS');
        Modkey = 'Meta';
    }

    Skink.dump('Modkey is ' + Modkey);

    shortcut.add(Modkey + Skink.Prefs.get('key-newEntry'),
    function() {
        $('#entrybox').focus();
    })

    shortcut.add('F5',
    function() {
        Skink.UI.reloadCurrentTab(true);
        Skink.restartReloadTimer();
    })

    shortcut.add(Skink.Prefs.get('key-reloadTimeline'),
    function() {
        Skink.UI.clearCurrentTimeline();
        Skink.UI.reloadCurrentTab(true, true);
        Skink.restartReloadTimer();
    })

    shortcut.add(Modkey + Skink.Prefs.get('key-showShortenWindow'),
    function() {
        Skink.UI.showShortLink();
    });

    shortcut.add(Modkey + '+Shift+M',
    function() {
        Skink.UI.markCurrentTimelineAsRead();
    });

    shortcut.add('F1',
    function() {
        Skink.UI.showHelp();
    });

    /*
		Added so we can open the preferences folder if the UI is hosed by bad CSS
	*/
    shortcut.add(Modkey + '+Shift+,',
    function() {
        Skink.Sys.openAppStorageFolder();
    });

    shortcut.add(Modkey + Skink.Prefs.get('key-reply'),
    function() {
        Skink.dump('getting screenname from current selection');
        var screenname = $('div.ui-selected .user-screen-name').text();
        var irt_id = $('div.ui-selected .entry-id').text().replace(/(\[|\])/g, '');

        if (screenname) {
            Skink.dump('username for reply is:' + screenname);
            // var username = '';
            Skink.UI.prepReply(screenname, irt_id);
        }
    },
    {
        'disable_in_input': false
    });

    // ****************************************
    // tabs shortcuts
    // ****************************************
    shortcut.add(Modkey + '+1', function() {
        Skink.UI.showTab(0);
    })
    shortcut.add(Modkey + '+2', function() {
        Skink.UI.showTab(1);
    })
    shortcut.add(Modkey + '+,', function() {
        Skink.UI.showPrefs()
    })

    // ****************************************
    // Keys to navigate timeline
    // ****************************************
    shortcut.add(Modkey + '+down',
    function() {
        Skink.Keyboard.move('down', '.reply');
    });
    shortcut.add(Modkey + '+up',
    function() {
        Skink.Keyboard.move('up', '.reply');
    });
    shortcut.add(Modkey + '+Shift+down',
    function() {
        Skink.Keyboard.move('down', '.dm');
    });
    shortcut.add(Modkey + '+Shift+up',
    function() {
        Skink.Keyboard.move('up', '.dm');
    });
    shortcut.add(Modkey + '+End',
    function() {
        Skink.Keyboard.move('down', ':last');
    });
    shortcut.add(Modkey + '+Home',
    function() {
        Skink.Keyboard.move('up', ':first');
    });
    shortcut.add('Down',
    function() {
        Skink.Keyboard.move('down');
    },
    {
        'disable_in_input': true
    });
    shortcut.add('Up',
    function() {
        Skink.Keyboard.move('up');
    },
    {
        'disable_in_input': true
    });
    shortcut.add(Modkey + '+J',
    function() {
        Skink.Keyboard.move('down');
    });
    shortcut.add(Modkey + '+K',
    function() {
        Skink.Keyboard.move('up');
    });
    shortcut.add('J',
    function() {
        Skink.Keyboard.move('down');
    },
    {
        'disable_in_input': true
    });
    shortcut.add('K',
    function() {
        Skink.Keyboard.move('up');
    },
    {
        'disable_in_input': true
    });

    /*
		Search box submit on Enter
	*/
    shortcut.add('Enter',
    function() {
        Skink.Section.search.build();
    },
    {
        target: $('#search-for')[0],
        propagate: false
    });

    // ****************************************
    // editor shortcuts
    // ****************************************
    shortcut.add(Modkey + '+B',
    function() {
        Skink.Editor.bold();
    },
    {
        target: $('#entrybox')[0],
        propagate: false
    });
    shortcut.add(Modkey + '+I',
    function() {
        Skink.Editor.italics();
    },
    {
        target: $('#entrybox')[0],
        propagate: false
    });
    shortcut.add(Modkey + Skink.Prefs.get('key-highlight-code'),
    function() {
        Skink.Editor.code();
    },
    {
        target: $('#entrybox')[0],
        propagate: false
    });
    shortcut.add(Modkey + '+U',
    function() {
        Skink.Editor.link();
    },
    {
        target: $('#entrybox')[0],
        propagate: false
    });
    shortcut.add('Enter',
    function() {
        Skink.UI.sendUpdate();
    },
    {
        target: $('#entrybox')[0],
        propagate: false
    });

    /*
		Username/password prefs -> save
	*/
    shortcut.add('Enter',
    function() {
        Skink.Prefs.setPrefs();
    },
    {
        target: $('#username')[0],
        propagate: false
    });
    shortcut.add('Enter',
    function() {
        Skink.Prefs.setPrefs();
    },
    {
        target: $('#password')[0],
        propagate: false
    });

}

Skink.Keyboard.move = function(dir, selector) {

    if (!selector) {
        selector = '';
    }

    Skink.dump("selector is '" + selector + "'")

    // var timelineid = 'timeline-friends';
    var section = Skink.Section.getSectionFromTab(Skink.UI.selectedTab)
    var timelineid = section.timeline;

    if (!dir) {
        dir = 'down'
    }

    if (dir == 'down') {
        var movefunc = 'nextAll';
        var wrapselc = 'first';
    } else if (dir == 'up') {
        dir = 'up'
        var movefunc = 'prevAll';
        var wrapselc = 'last';
    } else {
        return false;
    }

    // get current selected
    var jqsel = $('#' + timelineid + ' div.ui-selected');
    // air.trace('selected:'+jqsel.length);
    // air.trace('moving:'+movefunc+'/'+wrapselc+"\n"+'selected:'+jqsel.length);
    // if none selected, or there is no 'next', select first
    if (selector == ":first" || selector == ":last") {
        // air.trace('first in timeline');
        Skink.Keyboard.moveSelect($('#' + timelineid + ' div.timeline-entry:visible' + selector), section)
    } else if (jqsel.length == 0) {
        // air.trace('nothing is selected')
        Skink.Keyboard.moveSelect($('#' + timelineid + ' div.timeline-entry:visible' + selector + ':' + wrapselc), section)
        jqsel = $('#' + timelineid + ' div.timeline-entry.ui-selected' + selector);
    } else if (jqsel[movefunc]('div.timeline-entry' + selector).eq(0).length == 0) {
        // air.trace('we are at the beginning or end');
        if (Skink.Prefs.get('timeline-keyboardnavwrap')) {
            Skink.Keyboard.moveSelect($('#' + timelineid + ' div.timeline-entry:visible' + selector + ':' + wrapselc), section)
            jqsel = $('#' + timelineid + ' div.timeline-entry.ui-selected' + selector);
        } else {
            air.trace('NOT WRAPPING');
        }
    } else {
        // air.trace('something is now selected');
        Skink.Keyboard.moveSelect(jqsel[movefunc]('div.timeline-entry:visible' + selector).eq(0), section);
    }
    // if selected is at bottom, go to top
}

Skink.Keyboard.moveSelect = function(jqelement, section) {
    Skink.dump('Moving to new selected item');
    Skink.dump('timelineid:' + section.timeline);

    // unselect everything that is selected
    $('#' + section.timeline + ' div.timeline-entry.ui-selected').removeClass('ui-selected');

    if (entryId == Skink.UI.getStatusIdFromElement(jqelement[0])) {
        air.trace('entryId:' + entryId);
        Skink.DB.markEntryAsRead(entryId);
    }

    // select passed
    if (jqelement.length > 0) {
        air.trace("toggle ui-selected and scrollto");
        jqelement.toggleClass('ui-selected').addClass('read');

        var viewport_bottom = $('#' + section.wrapper).innerHeight();
        var selected_bottom = jqelement.position().top + jqelement.height();

        /*
			going down
		*/
        if (selected_bottom > viewport_bottom) {
            var scroll_offset = ($('#' + section.wrapper).innerHeight() - jqelement.height()) * -1;
            air.trace('scroll offset:' + scroll_offset);
            $('#' + section.wrapper).scrollTo(jqelement, {
                offset: scroll_offset,
                speed: 1
            });
        }

        /*
			going up
		*/
        if (jqelement.position().top < $('#' + section.wrapper).position().top) {
            $('#' + section.wrapper).scrollTo(jqelement, {
                offset: 0,
                speed: 1
            });
        }

    } else {
        air.trace("Problem - jqelement passed length = 0 - can't scroll to anything");
    }

    $().trigger('UNREAD_COUNT_CHANGED');
}

/******************************
 * Keyboard
 ******************************/
Skink.Keyboard.keyboardHandler = function(event) {
    e = event || window.event;
    el = e.srcElement || e.target;

    if (el.name) {
        return true;
    }

    if (e.which == 13 && e.srcElement.id == 'entrybox') {
        Skink.UI.sendUpdate();
        return false;
    }

    // debugging
    if (e.srcElement.id == 'home') {
        Skink.dump('keyboard Event =================');
        Skink.dump("keyIdentifier:" + e.keyIdentifier);
        Skink.dump("KeyCode:" + e.keyCode);
        Skink.dump("which:" + e.which);
        Skink.dump("type:" + e.type);
        Skink.dump("shift:" + e.shiftKey);
        Skink.dump("ctrl:" + e.ctrlKey);
        Skink.dump("alt:" + e.altKey);
        Skink.dump("meta:" + e.metaKey);
        Skink.dump("src:" + e.srcElement.id);
    }

    return true;
}